/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 *
 */
import path from 'path';

import { parseJsonText } from '@ohos/hvigor';
import fse from 'fs-extra';
import { OhosLogger } from './log/ohos-logger.js';

const log: OhosLogger = OhosLogger.getLogger('json-util');

export function getJson5Obj(json5path: string, encodingStr = 'utf-8'): any {
  if (!fse.existsSync(json5path)) {
    return undefined;
  }
  const text = fse.readFileSync(path.resolve(json5path), { encoding: encodingStr as BufferEncoding });

  try {
    return parseJsonText(text);
  } catch (e) {
    if (e instanceof SyntaxError) {
      const msg = e.message.split('at ');
      if (msg.length === 2) {
        log.printErrorExit('JSON_READER_SYNTAX_ERROR', [msg[0].trim(), json5path, msg[1].trim()]);
      }
    }
    log.printErrorExit('NOT_CORRECT_JSON_FORMAT', [json5path]);
  }
}

/**
 * 这个函数会抛异常，需要使用方try-catch
 *
 * @param json5path
 * @param encodingStr
 */
export function getJson5ObjThrowError(json5path: string, encodingStr = 'utf-8'): any {
  if (!fse.existsSync(json5path)) {
    return undefined;
  }
  const text = fse.readFileSync(path.resolve(json5path), { encoding: encodingStr as BufferEncoding });
  return parseJsonText(text);
}


/**
 * 合并两个String json的数据
 * @param data1
 * @param data2
 */
export function mergeStringJson(data1: any, data2: any) {
  const jsonData: { string: StringRes[] } = {
    string: [],
  };
  const nameData: Array<string> = [];
  data1?.string.forEach((item: StringRes) => {
    jsonData.string.push(item);
    nameData.push(item.name);
  });
  data2?.string.forEach((item: StringRes) => {
    if (!nameData.includes(item.name)) {
      jsonData.string.push(item);
    }
  });
  return jsonData;
}

export interface StringRes {
  name: string;
  value: string;
}
